package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.Exception.LyException;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {
    @Autowired
    CategoryBrandService categoryBrandService;
    @Autowired
    BrandService brandService;
    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        //0.健壮性判断
     page = Math.max(1, page);
     rows=Math.max(1,rows);
     //判断是否有搜索关键字
        boolean isNotBlank = StringUtils.isNotBlank(key);
        //1.分页查询
        Page<Brand> result = query().like(isNotBlank,"name", key)
                .or()
                .like(isNotBlank,"letter", key)
                .page(new Page<>(page, rows));
        //2.解析
        long total = result.getTotal();
        long pages = result.getPages();
        List<Brand> list = result.getRecords();
        //3.封装PageDTO并返回
        PageDTO<BrandDTO> dtoPageDTO = new PageDTO<>(total, pages, BrandDTO.convertEntityList(list));
        return dtoPageDTO;
    }

    @Override
    public List<BrandDTO> queryBrandByCategory(Long id) {
        //List<Brand> brands = this.baseMapper.queryByCategoryId(id);
        List<Brand> brands = getBaseMapper().queryByCategoryId(id);
        if (brands==null){
            throw new LyException("查询品牌失败",500);
        }
        return BrandDTO.convertEntityList(brands);
    }

    /**
     * 多张表的新增
     * @param brandDTO
     */
    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
     //1.新增品牌
        //1.1 把DTO转为PO
        Brand brand = brandDTO.toEntity(Brand.class);
        //1.2 新增品牌
        boolean success = save(brand);
        if (!success){
            throw new LyException("更新品牌失败!", 500);
        }
       //1.3 回显id
        Long brandId = brand.getId();
        //2.中间表的新增
        //2.1 获取与品牌有关的所有分类的id
        List<Long> categoryIds = brandDTO.getCategoryIds();
        //2.2 把分类的id与品牌的id组合,封装为CategoryBrand
         List<CategoryBrand> categoryBrands=new ArrayList<>(categoryIds.size());
         for (Long categoryId: categoryIds){
             CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
             categoryBrands.add(categoryBrand);
         }
         //2.3批量新增
        categoryBrandService.saveBatch(categoryBrands);

    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        //1.更新品牌
        boolean success = updateById(brandDTO.toEntity(Brand.class));
        if (!success){
            //更新失败,抛出异常
            throw new LyException("更新失败!",500);
        }
        //2.根据品牌id删除中间表数据
          success = categoryBrandService.remove(new QueryWrapper<CategoryBrand>()
                .eq("brand_id", brandDTO.getId()));
        if (!success){
            //更新失败,抛出异常
            throw new LyException("更新品牌失败，删除中间表数据出错",500);
        }
        //3.重新插入中间表数据
        List<CategoryBrand> collect = brandDTO.getCategoryIds().stream().map(id ->
                CategoryBrand.of(id, brandDTO.getId())).collect(Collectors.toList());
        //批量写入中间表
        categoryBrandService.saveBatch(collect);
    }

    @Override
    @Transactional
    public void deleteBrandById(Long id) {
        //1.根据品牌id删除品牌
        brandService.removeById(id);
        //2.删除中间表
        categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id" ,id));
    }

}